package org.KeyCrafter.obj.type;

import org.KeyCrafter.ds.dict.*;

import java.util.Iterator;
import java.util.Map;

public class DefaultHashType implements HashType{
    private static final DictType type = new MurmurHash2();
    Dict dict = new HashDict(type, null);

    @Override
    public byte encoding() {
        return KeyCrafter_ENCODING_HT;
    }

    @Override
    public Dict content() {
        return dict;
    }

    @Override
    public int set(Object field, Object value) {
        return dict.replace(field, value);
    }

    @Override
    public Object get(Object field) {
        Dict.Entry de;
        // 确保编码正确
        assert this.encoding() == KeyCrafter_ENCODING_HT;
        // 在字典中查找域（键）
        de = dict.find(field);
        // 键不存在
        if (de == null) {
            return null;
        }
        // 取出域（键）的值
        return de.getValue();
    }

    @Override
    public Iterator<Map.Entry> iterator() {
        DictIterator di = dict.getSafeIterator();
        return new Iterator<Map.Entry>() {
            @Override
            public boolean hasNext() {
                return di.hasNext();
            }

            @Override
            public Map.Entry next() {
                Dict.Entry next = di.next();
                return next == null ? null : new Map.Entry() {
                    @Override
                    public Object getKey() {
                        return next.getKey();
                    }

                    @Override
                    public Object getValue() {
                        return next.getValue();
                    }

                    @Override
                    public Object setValue(Object value) {
                        next.setValue(value);
                        return value;
                    }
                };
            }
        };
    }
}
